package com.iretailer.report.web.system;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.iretailer.report.base.BaseAction;
import com.iretailer.report.common.InternationalMessage;
import com.iretailer.report.dto.ReCompanies;
import com.iretailer.report.dto.ReUser;
import com.iretailer.report.model.Companies;
import com.iretailer.report.model.Config;
import com.iretailer.report.service.UserService;
import com.iretailer.report.util.JsonUtil;
import com.iretailer.report.util.RMap;
import com.iretailer.report.util.SecurityUserUtil;
import com.iretailer.report.util.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.text.MessageFormat;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;

/**
 * @Auther Bennie
 * @Date 2020/6/15 11:15
 * @Description
 */
@Slf4j
@RestController
public class LoginController extends BaseAction {

    @RequestMapping("/")
    public ModelAndView index() {
        ModelAndView result = new ModelAndView();
        result.setViewName("index");
        return result;
    }

    @RequestMapping("/loginOtherMsg.action")
    public Map<String, Object> loginOtherMsg(@RequestBody ReCompanies reCompanies) {
        if (StringUtil.notEmpty(reCompanies.getSecondaryDomain())) {
            Companies companies = companyService.getOne(new QueryWrapper<Companies>().lambda().eq(Companies::getSecondaryDomain, reCompanies.getSecondaryDomain()));
            if (companies != null) {
                return RMap.ok(companies);
            } else {
                return RMap.ok();
            }
        } else {
            return RMap.ok();
        }
    }


    @RequestMapping("/unauth.action")

    public Map<String, Object> unauth(HttpServletRequest request) {
        Map<String, Object> map = new HashMap<>(2);
        map.put("status", 1009);
        map.put("showText", InternationalMessage.PLEASE_LOGIN.getByLanguage(SecurityUserUtil.userLanguage(request)));
        return map;
    }

    @RequestMapping("/user/login.action")
    public Map<String, Object> login(@RequestBody ReUser reUser) {
        Config pr = configService.getOne(new QueryWrapper<Config>().lambda().eq(Config::getConfigKey, "password_regex"));
        if (pr != null && StringUtil.notEmpty(pr.getConfigValue())) {
            String password = reUser.getUserPass();
            List<Map<String, Object>> prMaps = JsonUtil.json2list(pr.getConfigValue());
            for (Map<String, Object> prMap : prMaps) {
                String regex = (String) prMap.get("regex");
                String errorMsg = (String) prMap.get("errorMsg");
                if (!Pattern.matches(regex, password)) {
                    return RMap.error(errorMsg);
                }
            }
        }
        Subject subject = SecurityUtils.getSubject();
        boolean companyStatus = "Company".equals(reUser.getLoginType());
        String userName = MessageFormat.format("{0}{1}{2}", companyStatus ? reUser.getCompanyName() : false,
                UserService.companyUserSplit, reUser.getUserName());
        UsernamePasswordToken token = new UsernamePasswordToken(userName, reUser.getUserPass());
        RMap result = null;
        try {
            subject.login(token);
            result = RMap.ok();
            result.put("data", "/briefs");
            result.put("userInfo", subject.getPrincipal());
            result.put("toke", subject.getSession().getId());
//             User user = SecurityUserUtil.currentUser(request);
//            request.getSession().setAttribute("UserInfo", user);
        } catch (LockedAccountException e) {
            result = RMap.error(InternationalMessage.LOGIN_FAILED_THE_USER_IS_FROZEN.getByLanguage(SecurityUserUtil.defaultLanguage()));
        } catch (AuthenticationException e) {
            result = RMap.error(InternationalMessage.USER_NAME_OR_PASSWORD_ERROR.getByLanguage(SecurityUserUtil.defaultLanguage()));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    @RequestMapping("/user/logout.action")
    public Map<String, Object> userLogout() {
        SecurityUtils.getSubject().logout();
        return RMap.ok();
    }

}
